package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.beans.Topic;
import service.Service;
import util.GetDate;
import util.Uuid;

/**
 * Servlet implementation class Publish
 */
@WebServlet("/servlet/Publish")
public class Publish extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Publish() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//获取request传参
		String qq = request.getParameter("qq");
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		String pwd = request.getParameter("pwd");
		//初始化其他参数
		String date =  GetDate.getDate();
		String topicId = Uuid.getRandomNumber();
		//初始化话题对象
		Topic t = new Topic();
		t.setQq(qq);
		t.setTitle(title);
		t.setContent(content);
		t.setDate(date);
		t.setPwd(pwd);
		t.setTopicId(topicId);
		
		Service service = new Service();
		try {
			if(service.addTopic(t)) {
				response.sendRedirect("../PublishSuccess.jsp?id="+topicId);
			}else {
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				
		        out.flush();//清空缓存
		        out.println("<script>");//输出script标签
		        out.println("alert('啊哦..发布失败!');");//js语句：输出alert语句
		        out.println("history.back();");//js语句：输出网页回退语句
		        out.println("</script>");//输出script结尾标签
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
